package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();


        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 添加员工
     * @param employeeDTO
     */
    @Override
    public void insertEmployee(EmployeeDTO employeeDTO) {
        log.debug("Service该请求的线程id:{}", Thread.currentThread().getId());
        log.debug("添加员工 employeeDTO: {}", employeeDTO);
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        //设置账号状态默认是启用状态用数字1表示
        employee.setStatus(StatusConstant.ENABLE);
        //设置新增员工时间为当前时间
//        employee.setCreateTime(LocalDateTime.now());
        //设置员工的修改时间为当前时间
//        employee.setUpdateTime(LocalDateTime.now());
        //设置默认的密码123456(需要加密入库)
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        //设置创建员工的人
//        employee.setCreateUser(BaseContext.getCurrentId());
        //设置修改员工的人
//        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.insert(employee);
    }

    /**
     * 分页查询
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageResult selectPage(EmployeePageQueryDTO employeePageQueryDTO) {
        //1.调用startPage方法开始分页，第一个参数页码，第二个参数是每页显示记录数
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());

        //这个Page对象里面有很多数据，比如总记录数，查询列表
        Page page=employeeMapper.select(employeePageQueryDTO);

        long total = page.getTotal();
        List<Employee> employeeList = page.getResult();

        //最终返回一个PageResult(包含总记录数和员工列表数据)
        return new PageResult(total,employeeList);
    }

    /**
     * 根据id查询员工
     * @param status
     * @param id
     */
    @Override
    public void updateStatus(Integer status,Long id) {
        log.debug("员工状态status:{},员工id:{}",status,id);
        //封装对象方式可以提供mapper层的sql的复用
        Employee employee = new Employee();
        employee.setId(id);
        employee.setStatus(status);
        employeeMapper.update(employee);
    }

    @Override
    public Employee getEmployeeById(Long id) {
        log.debug("员工id为:{}", id);
        Employee employee=employeeMapper.getEmployeeById(id);
        return employee;
    }

    @Override
    public void update(EmployeeDTO employeeDTO) {
        log.debug("修改员工employeeDTO:{}", employeeDTO);
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        //设置修改员工时间
//        employee.setUpdateTime(LocalDateTime.now());
        //设置修改员工的人为当前登录后台的员工
//        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.update(employee);
    }

}
